package com.idbk.chargestation.activity.pile;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.MainActivity;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonMyBookResult;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.dialog.DialogResult;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;

import java.util.Locale;

/**
 * 预约电桩提交 和 结果确认
 * @author lupc,zhx 
 *
 */
public class ActivityReservePileCommit extends BaseActivity implements OnClickListener {

	public final static String TAG = ActivityReservePileCommit.class.getSimpleName();

	public final static String STR_T_1 = "编    号：%s";
	public final static String STR_T_2 = "序列号：%s";
	public final static String STR_T_3 = "类    型：%s";
	public final static String STR_T_4 = "收    费：%s元 / %d分钟";

	public Context mContext;

	private TextView mTextPileNum, mTextPileSn, mTextPileType, mTextPileFee;

	private TextView mTextCost, mTextBespeakTime, mTextGun;

	private LinearLayout mLayoutGunChoose;
	
	private ImageView mImageView;

	/**
	 * 预约的分钟数
	 */
	private int mBespeakIndex = 1;

	private final static int[] BESPEAK_TIMES = new int[]{
		5, 15, 30
	};

	private final static String[] BESPEAK_TIMES_INFO = new String[]{
		"5分钟",
		"15分钟",
		"30分钟"
	};
	
	/**
	 * 预约的枪号
	 */
	private int mGunIndex = 0;

	private final static String[] GUN_CHOOSE = new String[]{
		"01", "02"
	};

	private String[] GUN_MULTI = new String[8];
	
	private final static String[] GUN_INFO = new String[]{
		"枪号01",
		"枪号02",
	};


	/**
	 * 当前选择的 电桩
	 */
	private JsonPointPile mCurrentPile = null;
	
	private DialogResult mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_reserve_pile_commit);

		setupView();

		setupData();
	}

	private void setupView(){
		setupToolBar2();//显示标题栏

		mContext = this;

		mTextPileNum = (TextView)findViewById(R.id.textview_pile_num);
		mTextPileSn = (TextView)findViewById(R.id.textview_pile_sn);
		mTextPileType = (TextView)findViewById(R.id.textview_pile_type);
		mTextPileFee = (TextView)findViewById(R.id.textview_pile_fee);
		mTextGun = (TextView)findViewById(R.id.textview_gun);

		mTextCost = (TextView)findViewById(R.id.textview_bespeak_cost);
		mTextBespeakTime = (TextView)findViewById(R.id.textview_bespeak_time);
		mImageView = (ImageView)findViewById(R.id.imageview);

		mLayoutGunChoose = (LinearLayout)findViewById(R.id.layout_gun_choose);
		findViewById(R.id.layout_bespeak_time).setOnClickListener(this);
		findViewById(R.id.textview_submit).setOnClickListener(this);
	}

	private void setupData(){
		mCurrentPile = getIntent().getParcelableExtra(JsonPointPile.KEY);
		if (mCurrentPile == null) {
			Toast.makeText(this, "错误：无法获取参数!", Toast.LENGTH_SHORT).show();
			finish();
		} else {
			int num = mCurrentPile.gunInfos.size();
			int free = 0;
			if (num > 2) {
				for (int i = 0, j = 0; i < num; i++) {
					if (mCurrentPile.gunInfos.get(i).gunStatus == 3) {
						free++;
						int gunNum = mCurrentPile.gunInfos.get(i).gunNum;
						String index = "0" + gunNum;
						GUN_MULTI[j] = index;
						j++;
					}
				}

				if (free > 0){
					mLayoutGunChoose.setVisibility(View.VISIBLE);
				}
				mTextPileNum.setText(String.format(STR_T_1, String.format(Locale.CHINA, "#%02d", mCurrentPile.pileNum)));
				mTextPileSn.setText(String.format(STR_T_2, mCurrentPile.pileSn));
				mTextPileType.setText(String.format(STR_T_3, JsonPointPile.getPileType(mCurrentPile.pileType)));
				mTextPileFee.setText(String.format(Locale.CHINA, STR_T_4, String.format(Locale.CHINA, "%.2f", mCurrentPile.bookMoney), mCurrentPile.perMinutes));

				mTextBespeakTime.setText(BESPEAK_TIMES_INFO[mBespeakIndex]);
				if (free == 1){
					mGunIndex = 0;
					mTextGun.setText("枪号" + GUN_MULTI[mGunIndex]);
					mImageView.setVisibility(View.GONE);
				}
				mTextGun.setText("枪号" + GUN_MULTI[mGunIndex]);
				refreshBespeakCost();

			} else if (num <= 2) {
				if (mCurrentPile.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_SINGLE_PHASE
						|| mCurrentPile.pileType == JsonPointPile.PILE_TYPE_AC_DOUBLE_GUN_THREE_PHASE) {
					mLayoutGunChoose.setVisibility(View.VISIBLE);
				}
				mTextPileNum.setText(String.format(STR_T_1, String.format(Locale.CHINA, "#%02d", mCurrentPile.pileNum)));
				mTextPileSn.setText(String.format(STR_T_2, mCurrentPile.pileSn));
				mTextPileType.setText(String.format(STR_T_3, JsonPointPile.getPileType(mCurrentPile.pileType)));
				mTextPileFee.setText(String.format(Locale.CHINA, STR_T_4, String.format(Locale.CHINA, "%.2f", mCurrentPile.bookMoney), mCurrentPile.perMinutes));

				mTextBespeakTime.setText(BESPEAK_TIMES_INFO[mBespeakIndex]);
				//判断枪能否预约
				if (mCurrentPile.gunA == JsonPointPile.STATUS_IDLE && mCurrentPile.gunB != JsonPointPile.STATUS_IDLE) {
					mGunIndex = 0;
					mTextGun.setText(GUN_INFO[mBespeakIndex]);
					mImageView.setVisibility(View.GONE);

				} else if (mCurrentPile.gunA != JsonPointPile.STATUS_IDLE && mCurrentPile.gunB == JsonPointPile.STATUS_IDLE) {
					mGunIndex = 1;
					mTextGun.setText(GUN_INFO[mBespeakIndex]);
					mImageView.setVisibility(View.GONE);

					// mCurrentPile.gunB == JsonPointPile.STATUS_IDLE 为真
				} else if (mCurrentPile.gunA == JsonPointPile.STATUS_IDLE) {
					mGunIndex = 0;
					mTextGun.setText(GUN_INFO[mBespeakIndex]);
					mLayoutGunChoose.setOnClickListener(this);

				} else {
					mGunIndex = 0;
					mTextGun.setText(GUN_INFO[mBespeakIndex]);
				}
				mTextGun.setText(GUN_INFO[mGunIndex]);
				refreshBespeakCost();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_submit:
			showMyProgressDialog(true,true,"提交中...");
			if (mCurrentPile.gunInfos.size() <= 2) {
				mMainRequest = ChargeStationAPI.bespeakPile(mCurrentPile.pileSn, BESPEAK_TIMES[mBespeakIndex], GUN_CHOOSE[mGunIndex], mResponse);
			}else if (mCurrentPile.gunInfos.size() > 2){
				mMainRequest = ChargeStationAPI.bespeakPile(mCurrentPile.pileSn, BESPEAK_TIMES[mBespeakIndex], GUN_MULTI[mGunIndex], mResponse);
			}
			break;
		case R.id.layout_bespeak_time:
			new AlertDialog.Builder(this)
			.setTitle("选择预约时长")
			.setCancelable(true)
			.setNegativeButton(R.string.common_cancel, null)
			.setSingleChoiceItems(BESPEAK_TIMES_INFO, mBespeakIndex, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					mBespeakIndex = which;

					mTextBespeakTime.setText(BESPEAK_TIMES_INFO[mBespeakIndex]);

					refreshBespeakCost();
				}
			})
			.create()
			.show();
			break;
		case R.id.layout_gun_choose:
			if (mCurrentPile.gunInfos.size() <= 2) {
				new AlertDialog.Builder(this)
						.setTitle("选择预约枪号")
						.setCancelable(true)
						.setNegativeButton(R.string.common_cancel, null)
						.setSingleChoiceItems(GUN_INFO, mGunIndex, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								mGunIndex = which;
								mTextGun.setText(GUN_INFO[mGunIndex]);
							}
						})
						.create()
						.show();
			}else if (mCurrentPile.gunInfos.size() > 2){
				new AlertDialog.Builder(this)
						.setTitle("选择预约枪号")
						.setCancelable(true)
						.setNegativeButton(R.string.common_cancel, null)
						.setSingleChoiceItems(GUN_MULTI, mGunIndex, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								mGunIndex = which;
								mTextGun.setText("枪号" + GUN_MULTI[mGunIndex]);
							}
						})
						.create()
						.show();
			}
			break;
		default:
			break;
		}
	}

	//预约成功提示框，成功退出当前界面
	private void successDialog(String msg) {
		mDialog = new DialogResult(ActivityReservePileCommit.this, true,"预约成功", msg);
		mDialog.show();
		mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (mDialog != null) {
					mDialog.dismiss();
				}
				Intent intent = new Intent(mContext, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}
	
	//预约失败提示框，失败不退出界面，可再次请求
	private void failedDialog(String msg) {
		mDialog = new DialogResult(ActivityReservePileCommit.this, false, "预约失败", msg);
		mDialog.show();
	}
	
	private final EHttpResponse mResponse = new EHttpResponse() {

		@Override
		public void onEResponse(String response) {
			JsonMyBookResult result = GsonUtils.toBean(JsonMyBookResult.class, response);
			if (result == null){
				failedDialog("获取服务器数据为空");
				
			} else if(result.status == GlobalResult.OK.getStatus()){
				successDialog("你可以在  '我的 -> 我的预约' 查看详情");
				
			}  else if(result.status == GlobalResult.TOKEN_INVALID.getStatus()
					|| result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {
				jumpToLogin(ActivityReservePileCommit.this, false);
				
			} else {
				failedDialog(result.message);
			}
			
		}

		@Override
		public void onEErrorResponse(VolleyError error) {
			failedDialog("抱歉，当前电桩预约失败，请重新预约");
			Log.d(TAG, error.toString());
		}

		@Override
		public void onEFinish() {
			super.onEFinish();
			dismissMyProgressDialog();
		}

	};	

	private void refreshBespeakCost(){
		//输入判断
		if (mCurrentPile == null) {
			Log.e(TAG, "当前电桩对象为空，无法更新");
			return;
		}
		String t;
		if (mCurrentPile.perMinutes == 0) {
			t = "0.00";
			Log.e(TAG, "当前电桩 有参数为0，无法计算");
		} else {
			//计算价钱
			boolean flag = false;
			if (BESPEAK_TIMES[mBespeakIndex] % mCurrentPile.perMinutes == 0) {
				flag = true;
			}
			// 预约所需金额
			double result = mCurrentPile.bookMoney
					* (BESPEAK_TIMES[mBespeakIndex] / mCurrentPile.perMinutes + (flag ? 0 : 1));
			t = String.format(Locale.CHINA, "%.2f", result);
		}
		String value = " ￥ " + t;
		mTextCost.setText(value);
	}

}
